// utils/request.js
import axios from 'axios';
import { generateSignedParams } from './signUtil';

const baseURL = '/api'; // ✅ 替换为你自己的后台地址

const service = axios.create({
  baseURL,
  timeout: 10000,
});

// 请求拦截器：自动加签名参数
service.interceptors.request.use(config => {
  const urlPath = config.url.replace(baseURL, '').split('?')[0];

  const signParams = generateSignedParams(urlPath);

  if (config.method === 'get' || config.method === 'delete') {
    config.params = {
      ...(config.params || {}),
      ...signParams,
    };
  } else {
    config.params = {
      ...(config.params || {}),
      ...signParams,
    };
    // POST/PUT body 也可以加签（根据需要）
  }

  return config;
}, error => {
  return Promise.reject(error);
});

// 响应拦截器（可选：统一错误处理）
service.interceptors.response.use(
  res => res.data,
  err => {
    console.error('请求出错：', err);
    return Promise.reject(err);
  }
);

export default {
  get(url, params = {}, config = {}) {
    return service.get(url, { params, ...config });
  },
  post(url, data = {}, config = {}) {
    return service.post(url, data, config);
  },
  put(url, data = {}, config = {}) {
    return service.put(url, data, config);
  },
  delete(url, params = {}, config = {}) {
    return service.delete(url, { params, ...config });
  },
  rawInstance: service, // 如果你想手动使用原始 axios 实例
};
